import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

export class CameraManager {
  private camera: THREE.PerspectiveCamera
  private controls: OrbitControls
  private rendererDomElement: HTMLElement

  constructor(rendererDomElement: HTMLElement) {
    this.rendererDomElement = rendererDomElement
    // 创建透视相机
    this.camera = new THREE.PerspectiveCamera(
      75, // 视角
      window.innerWidth / window.innerHeight, // 宽高比
      0.1, // 近平面
      1000 // 远平面
    )

    // 设置相机位置
    this.camera.position.set(0, 30, 70); // 将相机拉远并抬高一些
    this.camera.lookAt(0, 0, 0)

    // 创建轨道控制器，使用传入的 renderer DOM element
    this.controls = new OrbitControls(this.camera, this.rendererDomElement)
    this.controls.enableDamping = true // 启用阻尼效果
    this.controls.dampingFactor = 0.05
    this.controls.screenSpacePanning = false
    this.controls.minDistance = 3
    this.controls.maxDistance = 30
    this.controls.maxPolarAngle = Math.PI / 2

    // 监听窗口大小变化
    window.addEventListener('resize', this.onWindowResize.bind(this))
  }

  private onWindowResize(): void {
    this.camera.aspect = window.innerWidth / window.innerHeight
    this.camera.updateProjectionMatrix()
    // Renderer size is handled by RendererManager, but OrbitControls might need update if renderer size changes relative to window
    // No direct renderer.setSize here anymore
  }

  public getCamera(): THREE.PerspectiveCamera {
    return this.camera
  }

  public getControls(): OrbitControls {
    return this.controls
  }

  public update(): void {
    this.controls.update()
  }
}
